package gold.contest;

import gold.utils.InputUtil;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created by fanzhenyu02 on 2020/6/27.
 * common problem solver template.
 */
public class LC5683 {
    public long startExecuteTime = System.currentTimeMillis();

    /*
     * @param 此题目参考了别人代码
     * 不是因为复杂，而是因为经典
     * 未来需要再次复习此道题目
     * 不得不说插空发真是一个好办法
     * @return:
     */
    class Solution {
        public int[] rearrangeArray(int[] nums) {

            int[] res = new int[nums.length];
            int[] small = new int[nums.length / 2];
            int[] big = new int[nums.length - small.length];

            Arrays.sort(nums);

            for (int i = 0; i < small.length; i++) {
                small[i] = nums[i];
            }
            for (int i = small.length; i < nums.length; i++) {
                big[i - small.length] = nums[i];
            }

            for (int i = 0; i < small.length; i++) {
                res[2 * i + 1] = small[i];
            }

            for (int i = 0; i < big.length; i++) {
                res[2 * i] = big[i];
            }

            return res;
        }
    }

    class Solution_Fail {
        public int[] rearrangeArray(int[] nums) {
            Arrays.sort(nums);
            for (int i = 1; i < nums.length - 1; i++) {
                if ((nums[i - 1] + nums[i + 1]) / 2 == nums[i]) {
                    // i don'nt match, switch i+1 and i+2;
                    if (i + 2 < nums.length) {
                        swapPos(nums, i + 1, i + 2);
                    } else {
                        // swap i and i+1
                        swapPos(nums, i + 1, i);
                    }
                }
            }

            return nums;
        }

        public void swapPos(int[] nums, int i, int j) {
            int temp = nums[i];
            nums[i] = nums[j];
            nums[j] = temp;
        }
    }

    public void run() {
        Solution solution = new Solution();
        int[] arr = InputUtil.toIntegerArray("[13,31,55,75,51,67,10,50,39,95,43,28,42,99,21,9,65,81,14,24,44,93,82,18,30,32,25,22,77,19,97,83,98]");
        arr = solution.rearrangeArray(arr);
        System.out.println(Arrays.toString(arr));
        checkWhereMisMatch(arr);
    }

    public void checkWhereMisMatch(int[] nums) {
        for (int i = 1; i < nums.length - 1; i++) {
            if ((nums[i - 1] + nums[i + 1]) / 2 == nums[i]) {
                System.out.print(i + " , ");
            }
        }
    }

    public static void main(String[] args) throws Exception {
        LC5683 an = new LC5683();
        an.run();

        System.out.println("\ncurrent solution total execute time: " + (System.currentTimeMillis() - an.startExecuteTime) + " ms.");
    }
}
